﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Helpers;
using Model;
using System.IO;

namespace FEIStorageSite
{
    public partial class Upload : System.Web.UI.Page
    {
        private const int MAX_FILE_LENGHT = 15728640;

        protected void Page_Load(object sender, EventArgs e)
        {
            DAL.connectionString = "Data Source=" + Server.MapPath("App_Data\\fei_storage.db");

            uploadPageTitle.Text = "<h3>Upload file</h3>";
            
            if (!IsPostBack)
            {
                categoriesList.DataSource = DAL.GetCategories();
                categoriesList.DataBind();
            }
        }

        public void UploadButtonClick(Object sender, EventArgs e)
        {
            try
            {
                uploadCaptcha.ValidateCaptcha(captchaTextBox.Text);

                if ((fileUpload.PostedFile == null) || (fileUpload.PostedFile.ContentLength == 0))
                {
                    throw new Exception("Виберіть файл");
                }
                else if(nameTextBox.Text == String.Empty)
                {
                    throw new Exception("Введіть назву файла");
                }
                else if (descriptionTextBox.Text == String.Empty)
                {
                    throw new Exception("Введіть опис файла");
                }
                else if (!uploadCaptcha.UserValidated)
                {
                    throw new Exception("Ви неправильно ввели текст з малюнка");
                }
                else if (fileUpload.PostedFile.ContentLength > MAX_FILE_LENGHT)
                {
                    throw new Exception("Розмір файла перевищує 15 мб");
                }
                else
                {
                    string fileName = System.IO.Path.GetFileName(fileUpload.PostedFile.FileName);
                    fileName = fileName.Replace(" ", "_");

                    DirectoryInfo storageDir = new DirectoryInfo(Server.MapPath("storage/"));
                    FileInfo[] filesList = storageDir.GetFiles(fileName);

                    while (filesList.Length != 0)
                    {
                        fileName = "c_" + fileName;
                        filesList = storageDir.GetFiles(fileName);
                    }

                    uploadPageError.Text = fileName;
                    string saveLocation = (Server.MapPath("storage/") + fileName);
                    fileUpload.PostedFile.SaveAs(saveLocation);
                    FileItem file = new FileItem(0, "storage/" + fileName, nameTextBox.Text, descriptionTextBox.Text, Request.ServerVariables["REMOTE_ADDR"], DateTime.Now, Convert.ToInt32(categoriesList.SelectedValue), 0);
                    int ID = DAL.SaveFile(file);
                    Response.Redirect("Download.aspx?type=file&id=" + ID.ToString());
                }
            }
            catch (Exception exception)
            {
                uploadPageError.Text = "Помилка: " + exception.Message;
            }
        }
    }
}
